/**
 * financial-products.js - 理财产品相关功能模块
 * 处理产品列表加载和展示功能
 */

/**
 * 加载产品列表
 */
function loadProducts() {
  const productsList = document.getElementById('products-list');
  
  // 显示加载中
  productsList.innerHTML = `
    <div class="loader-container">
      <div class="loader"></div>
    </div>
  `;
  
  // 构建请求参数
  const params = {
    page: currentPage,
    size: pageSize
  };
  
  // 添加筛选条件
  if (currentFilters.riskLevels && currentFilters.riskLevels.length > 0) {
    params.riskLevel = currentFilters.riskLevels.join(',');
  }
  
  if (currentFilters.durations && currentFilters.durations.length > 0) {
    if (currentFilters.durations.includes('short')) {
      params.maxDuration = 30;
    }
    if (currentFilters.durations.includes('medium')) {
      params.minDuration = params.minDuration || 31;
      params.maxDuration = 180;
    }
    if (currentFilters.durations.includes('long')) {
      params.minDuration = 181;
    }
  }
  
  if (currentFilters.minReturn) {
    params.minReturn = currentFilters.minReturn;
  }
  
  // 只显示在售的产品
  params.status = 1;
  
  // 调用API获取产品列表
  ApiService.get('/api/finance/product/list', params)
    .then(response => {
      if (response.code === 0 && response.data) {
        const products = response.data.list || [];
        const total = response.data.total || 0;
        
        // 计算总页数
        totalPages = Math.ceil(total / pageSize);
        
        // 更新分页状态
        updatePagination();
        
        // 渲染产品列表
        renderProducts(products);
      } else {
        throw new Error(response.message || '获取产品列表失败');
      }
    })
    .catch(error => {
      console.error('获取产品列表失败:', error);
      productsList.innerHTML = `
        <div class="empty-state">
          <i class="fas fa-exclamation-circle mb-3" style="font-size: 48px; color: var(--light-text);"></i>
          <p>产品加载失败，请稍后再试</p>
        </div>
      `;
    });
}

/**
 * 渲染产品列表
 * @param {Array} products 产品数组
 */
function renderProducts(products) {
  const productsList = document.getElementById('products-list');
  
  if (products.length === 0) {
    productsList.innerHTML = `
      <div class="empty-state">
        <i class="fas fa-search mb-3" style="font-size: 48px; color: var(--light-text);"></i>
        <p>暂无符合条件的产品</p>
      </div>
    `;
    return;
  }
  
  let productsHtml = '';
  products.forEach(product => {
    // 计算售出百分比
    const soldPercentage = product.soldAmount / product.totalAmount * 100;
    
    // 风险等级样式
    let riskClass = 'low';
    let riskName = '低风险';
    if (product.riskLevel === 2) {
      riskClass = 'medium';
      riskName = '中风险';
    } else if (product.riskLevel === 3) {
      riskClass = 'high';
      riskName = '高风险';
    }
    
    // 状态样式
    let statusClass = 'selling';
    let statusName = '发售中';
    if (product.status === 2) {
      statusClass = 'sold-out';
      statusName = '已售罄';
    } else if (product.status === 3) {
      statusClass = 'expired';
      statusName = '已到期';
    }
    
    productsHtml += `
      <div class="product-card" data-id="${product.id}">
        <div class="product-card-header">
          <div class="product-card-title">${product.productName}</div>
          <div class="product-card-code">${product.productCode}</div>
        </div>
        <div class="product-card-body">
          <div class="product-card-info">
            <div class="product-card-item">
              <div class="product-card-label">预期年化收益率</div>
              <div class="product-card-value accent">${product.expectedReturn}%</div>
            </div>
            <div class="product-card-item">
              <div class="product-card-label">投资期限</div>
              <div class="product-card-value">${product.duration}天</div>
            </div>
            <div class="product-card-item">
              <div class="product-card-label">起投金额</div>
              <div class="product-card-value">¥${product.minAmount.toLocaleString()}</div>
            </div>
            <div class="product-card-item">
              <div class="product-card-label">销售进度</div>
              <div class="product-card-value">${soldPercentage.toFixed(0)}%</div>
            </div>
          </div>
          
          <div class="product-card-progress">
            <div class="product-progress-bar">
              <div class="product-progress-fill" style="width: ${soldPercentage}%"></div>
            </div>
            <div class="product-progress-values">
              <span>¥0</span>
              <span>¥${product.soldAmount.toLocaleString()}</span>
              <span>¥${product.totalAmount.toLocaleString()}</span>
            </div>
          </div>
        </div>
        <div class="product-card-footer">
          <div class="product-risk ${riskClass}">${riskName}</div>
          <div class="product-status ${statusClass}">${statusName}</div>
        </div>
      </div>
    `;
  });
  
  productsList.innerHTML = productsHtml;
  
  // 添加点击事件，打开产品详情
  document.querySelectorAll('.product-card').forEach(card => {
    card.addEventListener('click', () => {
      const productId = card.getAttribute('data-id');
      openProductDetail(productId);
    });
  });
}

/**
 * 加载热门产品
 */
function loadHotProducts() {
  const hotProductsList = document.getElementById('hot-products-list');
  
  // 显示加载中
  hotProductsList.innerHTML = `
    <div class="loader-container">
      <div class="loader"></div>
    </div>
  `;
  
  // 调用API获取热门产品
  ApiService.get('/api/finance/product/hot', { limit: 4 })
    .then(response => {
      if (response.code === 0 && response.data) {
        const products = response.data.list || [];
        
        // 使用相同的渲染函数，但目标元素不同
        if (products.length === 0) {
          hotProductsList.innerHTML = `
            <div class="empty-state">
              <i class="fas fa-fire-alt mb-3" style="font-size: 48px; color: var(--light-text);"></i>
              <p>暂无热门产品</p>
            </div>
          `;
          return;
        }
        
        let productsHtml = '';
        products.forEach(product => {
          // 计算售出百分比
          const soldPercentage = product.soldAmount / product.totalAmount * 100;
          
          // 风险等级样式
          let riskClass = 'low';
          let riskName = '低风险';
          if (product.riskLevel === 2) {
            riskClass = 'medium';
            riskName = '中风险';
          } else if (product.riskLevel === 3) {
            riskClass = 'high';
            riskName = '高风险';
          }
          
          // 状态样式
          let statusClass = 'selling';
          let statusName = '发售中';
          if (product.status === 2) {
            statusClass = 'sold-out';
            statusName = '已售罄';
          } else if (product.status === 3) {
            statusClass = 'expired';
            statusName = '已到期';
          }
          
          productsHtml += `
            <div class="product-card" data-id="${product.id}">
              <div class="product-card-header">
                <div class="product-card-title">${product.productName}</div>
                <div class="product-card-code">${product.productCode}</div>
              </div>
              <div class="product-card-body">
                <div class="product-card-info">
                  <div class="product-card-item">
                    <div class="product-card-label">预期年化收益率</div>
                    <div class="product-card-value accent">${product.expectedReturn}%</div>
                  </div>
                  <div class="product-card-item">
                    <div class="product-card-label">投资期限</div>
                    <div class="product-card-value">${product.duration}天</div>
                  </div>
                  <div class="product-card-item">
                    <div class="product-card-label">起投金额</div>
                    <div class="product-card-value">¥${product.minAmount.toLocaleString()}</div>
                  </div>
                  <div class="product-card-item">
                    <div class="product-card-label">销售进度</div>
                    <div class="product-card-value">${soldPercentage.toFixed(0)}%</div>
                  </div>
                </div>
                
                <div class="product-card-progress">
                  <div class="product-progress-bar">
                    <div class="product-progress-fill" style="width: ${soldPercentage}%"></div>
                  </div>
                  <div class="product-progress-values">
                    <span>¥0</span>
                    <span>¥${product.soldAmount.toLocaleString()}</span>
                    <span>¥${product.totalAmount.toLocaleString()}</span>
                  </div>
                </div>
              </div>
              <div class="product-card-footer">
                <div class="product-risk ${riskClass}">${riskName}</div>
                <div class="product-status ${statusClass}">${statusName}</div>
              </div>
            </div>
          `;
        });
        
        hotProductsList.innerHTML = productsHtml;
        
        // 添加点击事件，打开产品详情
        document.querySelectorAll('#hot-products-list .product-card').forEach(card => {
          card.addEventListener('click', () => {
            const productId = card.getAttribute('data-id');
            openProductDetail(productId);
          });
        });
      } else {
        throw new Error(response.message || '获取热门产品失败');
      }
    })
    .catch(error => {
      console.error('获取热门产品失败:', error);
      hotProductsList.innerHTML = `
        <div class="empty-state">
          <i class="fas fa-exclamation-circle mb-3" style="font-size: 48px; color: var(--light-text);"></i>
          <p>热门产品加载失败，请稍后再试</p>
        </div>
      `;
    });
}

/**
 * 加载我的理财产品
 */
function loadMyProducts() {
  const myProductsList = document.getElementById('my-products-list');
  
  // 显示加载中
  myProductsList.innerHTML = `
    <div class="loader-container">
      <div class="loader"></div>
    </div>
  `;
  
  // 调用API获取我的理财订单列表
  ApiService.get('/api/finance/order/list', { page: 1, size: 10 })
    .then(response => {
      if (response.code === 0 && response.data) {
        const orders = response.data.list || [];
        
        if (orders.length === 0) {
          myProductsList.innerHTML = `
            <div class="empty-state">
              <i class="fas fa-wallet mb-3" style="font-size: 48px; color: var(--light-text);"></i>
              <p>您还没有购买任何理财产品</p>
              <button class="btn btn-primary mt-3" id="go-buy-btn">去购买</button>
            </div>
          `;
          
          // 添加按钮事件
          const goBuyBtn = document.getElementById('go-buy-btn');
          if (goBuyBtn) {
            goBuyBtn.addEventListener('click', () => {
              document.querySelector('.financial-tab[data-tab="all"]').click();
            });
          }
          
          return;
        }
        
        let ordersHtml = '';
        orders.forEach(order => {
          // 状态样式
          let statusClass = 'processing';
          let statusName = '处理中';
          
          switch (order.status) {
            case 1:
              statusClass = 'active';
              statusName = '已生效';
              break;
            case 2:
              statusClass = 'expired';
              statusName = '已到期';
              break;
            case 3:
              statusClass = 'canceled';
              statusName = '已取消';
              break;
          }
          
          // 格式化日期
          const purchaseTime = new Date(order.purchaseTime).toLocaleDateString();
          const valueTime = order.valueTime ? new Date(order.valueTime).toLocaleDateString() : '-';
          const dueTime = order.dueTime ? new Date(order.dueTime).toLocaleDateString() : '-';
          
          ordersHtml += `
            <div class="my-product-item" data-id="${order.id}">
              <div class="my-product-header">
                <div class="my-product-title">
                  ${order.productName}
                  <span class="my-product-status ${statusClass}">${statusName}</span>
                </div>
                <div class="my-product-no">${order.orderNo}</div>
              </div>
              <div class="my-product-body">
                <div class="my-product-item-group">
                  <div class="my-product-label">投资金额</div>
                  <div class="my-product-value">¥${order.amount.toLocaleString()}</div>
                </div>
                <div class="my-product-item-group">
                  <div class="my-product-label">预期收益</div>
                  <div class="my-product-value accent">¥${order.expectedProfit.toLocaleString()}</div>
                </div>
                <div class="my-product-item-group">
                  <div class="my-product-label">购买时间</div>
                  <div class="my-product-value">${purchaseTime}</div>
                </div>
                <div class="my-product-item-group">
                  <div class="my-product-label">起息时间</div>
                  <div class="my-product-value">${valueTime}</div>
                </div>
                <div class="my-product-item-group">
                  <div class="my-product-label">到期时间</div>
                  <div class="my-product-value">${dueTime}</div>
                </div>
                <div class="my-product-item-group">
                  <div class="my-product-label">实际收益</div>
                  <div class="my-product-value accent">${order.actualProfit ? '¥' + order.actualProfit.toLocaleString() : '-'}</div>
                </div>
              </div>
              <div class="my-product-footer">
                <button class="btn btn-outline-primary view-order-detail-btn" data-id="${order.id}">查看详情</button>
              </div>
            </div>
          `;
        });
        
        myProductsList.innerHTML = ordersHtml;
        
        // 添加详情按钮事件
        document.querySelectorAll('.view-order-detail-btn').forEach(button => {
          button.addEventListener('click', (event) => {
            event.stopPropagation();
            const orderId = button.getAttribute('data-id');
            window.location.href = `/investment-detail.html?id=${orderId}`;
          });
        });
      } else {
        throw new Error(response.message || '获取我的理财订单失败');
      }
    })
    .catch(error => {
      console.error('获取我的理财订单失败:', error);
      myProductsList.innerHTML = `
        <div class="empty-state">
          <i class="fas fa-exclamation-circle mb-3" style="font-size: 48px; color: var(--light-text);"></i>
          <p>订单加载失败，请稍后再试</p>
        </div>
      `;
    });
}

/**
 * 打开产品详情
 * @param {string} productId 产品ID
 */
function openProductDetail(productId) {
  const modal = document.getElementById('product-detail-modal');
  
  // 重置购买表单
  document.getElementById('purchase-amount').value = '';
  document.getElementById('expected-return').textContent = '¥0.00';
  document.getElementById('purchase-agreement').checked = false;
  
  // 调用API获取产品详情
  ApiService.get(`/api/finance/product/${productId}`)
    .then(response => {
      if (response.code === 0 && response.data) {
        const product = response.data;
        
        // 保存当前产品详情到全局变量
        currentProductDetail = product;
        
        // 更新详情页面
        document.getElementById('product-detail-title').textContent = '产品详情';
        document.getElementById('product-detail-name').textContent = product.productName;
        document.getElementById('product-detail-code').textContent = product.productCode;
        document.getElementById('product-detail-return').textContent = product.expectedReturn + '%';
        document.getElementById('product-detail-duration').textContent = product.duration + '天';
        document.getElementById('product-detail-min-amount').textContent = '¥' + product.minAmount.toLocaleString();
        document.getElementById('product-detail-max-amount').textContent = product.maxAmount ? '¥' + product.maxAmount.toLocaleString() : '无限制';
        
        // 风险等级
        let riskName = '低风险';
        if (product.riskLevel === 2) {
          riskName = '中风险';
        } else if (product.riskLevel === 3) {
          riskName = '高风险';
        }
        document.getElementById('product-detail-risk').textContent = riskName;
        
        document.getElementById('product-detail-total').textContent = '¥' + product.totalAmount.toLocaleString();
        
        // 销售期限
        const startTime = new Date(product.startTime).toLocaleDateString();
        const endTime = new Date(product.endTime).toLocaleDateString();
        document.getElementById('product-detail-sale-period').textContent = startTime + ' ~ ' + endTime;
        
        // 起息日和到期日
        document.getElementById('product-detail-value-date').textContent = product.valueDate;
        
        // 销售进度
        const soldPercentage = product.soldAmount / product.totalAmount * 100;
        document.getElementById('product-detail-sold-percentage').textContent = soldPercentage.toFixed(0);
        document.getElementById('product-progress-fill').style.width = soldPercentage + '%';
        document.getElementById('product-detail-sold-amount').textContent = '¥' + product.soldAmount.toLocaleString();
        document.getElementById('product-detail-total-amount').textContent = '¥' + product.totalAmount.toLocaleString();
        
        // 产品描述
        document.getElementById('product-detail-desc').textContent = product.productDesc || '暂无详细描述';
        
        // 购买金额提示
        document.getElementById('purchase-amount-hint').textContent = `最低${product.minAmount.toLocaleString()}元${product.maxAmount ? '，最高' + product.maxAmount.toLocaleString() + '元' : ''}`;
        
        // 显示模态框
        modal.style.display = 'block';
      } else {
        throw new Error(response.message || '获取产品详情失败');
      }
    })
    .catch(error => {
      console.error('获取产品详情失败:', error);
      Toast.error('获取产品详情失败，请稍后再试');
    });
}
